/*
 * @Description:
 * @Author: Rfan
 * @Date: 2022-01-05 09:49:35
 * @LastEditTime: 2022-11-17 19:44:53
 */

import { useState, useEffect, Suspense } from 'react';
import { ConfigProvider, Spin } from 'antd';
import flatten from 'flat';
import dayjs from 'dayjs';
import { BrowserRouter } from 'react-router-dom';
import { observer } from 'mobx-react-lite';
import { IntlProvider } from 'react-intl';
import RouteList from './routes/index';
import { appState, appActions } from './store/mobx';
import 'dayjs/locale/zh-cn';

import Layout from '@/layout';

function importMessages(locale: string) {
  switch (locale) {
    case 'en':
      return import('./locale/en_US.json');
    default:
      return import('./locale/zh_CN.json');
  }
}

function importAntdLang(locale: string) {
  switch (locale) {
    case 'en':
      return import('antd/lib/locale/en_US');
    default:
      return import('antd/lib/locale/zh_CN');
  }
}

function App() {
  const locale = appState.lang;
  const [messages, setMessages] = useState({});
  const [antdLang, setAntdLang] = useState(null);

  useEffect(() => {
    // 获取单位列表
    appActions.getUnitList();
  }, [appState.realName]);

  useEffect(() => {
    importMessages(locale).then(setMessages);
    importAntdLang(locale).then((res) => {
      setAntdLang(res.default);
    });
    dayjs.locale(locale);
  }, [locale]);

  return (
    <ConfigProvider locale={antdLang}>
      <IntlProvider
        messages={flatten(messages)}
        locale={appState.lang}
        key={appState.lang}
        defaultLocale="zh-CN"
      >
        <BrowserRouter basename="/">
          <Suspense fallback={<Layout />}>
            <RouteList />
          </Suspense>
        </BrowserRouter>
      </IntlProvider>
    </ConfigProvider>
  );
}

export default observer(App);
